<?php

namespace Index\Controller;

use Think\Controller;

class IndexController extends BaseController {

    public function __construct()
    {
        parent::__construct();
        $sys = M('Sys')->select();
        foreach($sys as $k=>$v){
            if($v['name'] == 'currency_name'){
                $this->assign('B', $v['value']);
            }elseif($v['name'] == 'list'){
                $this->assign('now_list',$v['value']);
            }elseif($v['name'] == 'gzjs'){
                if(strlen($v['value'])>400){
                    $this->assign('gzjs',$this->msubstr($v['value'],0,250));
                }else {
                    $this->assign('gzjs', $v['value']);
                }
            } elseif ($v['name'] == 'jc_text') {
                $arr = explode("<>", $v['value']);
                $arr1 = array();
                foreach($arr as $k => $v){
                    $arr1[$k]['text'] = $v;
                }
                $this->assign('jc_text', $arr1);
            } else{
                $this->assign(''.$v['name'], $v['value']);
            }
        }
        $userId = trim(session('userId'));
        if($userId){
            $username = M("User")->where("id = $userId")->getField("username");
            if(strlen($username)>16){
                $username = change_username($username);
            }
            $this->assign('username', $username);
        }
        $this->assign('lang', $this->lang("zh"));

        $status = M("User")->where(array("id"=>$userId))->getField("status");
        if($status == 1){
            $this->error('您的账号已被冻结！', U('User/Index/logout'));
            die;
        }


    }

    function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
    {
            if(function_exists("mb_substr")){
                if($suffix)
                    return mb_substr($str, $start, $length, $charset)."...";
                else
                    return mb_substr($str, $start, $length, $charset);
            }
            elseif(function_exists('iconv_substr')) {
                if($suffix)
                    return iconv_substr($str,$start,$length,$charset)."...";
                else
                    return iconv_substr($str,$start,$length,$charset);
            }
            $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
            $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
            $re['gbk']  = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
            $re['big5']  = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
            if($suffix) return $slice."…";
            return $slice;
    }



    public function index(){
        $in_pond = M("Sys")->where(array("name"=>"in_pond"))->getField("value");
        $pond = M("Sys")->where(array("name"=>"pond"))->getField("value");
        $seat_on = M("Sys")->where(array("name"=>"seat_on"))->getField("value");
        if($seat_on == 1 && $pond == 0){
            $d['value'] = $in_pond*15;
            M("Sys")->where(array("name"=>"pond"))->save($d);
            $this->assign("pond", $in_pond*15);
        }

        $islogin =  !empty($_SESSION['userId'])?$_SESSION['userId']:0;
        $this->assign('islogin',$islogin);
        if($islogin >0){
            $status = M("User")->where(array("id"=>$_SESSION['userId']))->getField("status");
            if($status == 1){
                $this->error('您的账号已被冻结！');
                die;
            }
            $username = M("User")->where(array("id"=>$islogin))->getField("username");
            $this->assign('username',$username);
        }
        /*最后一位占位者*/
        $lasttime = M("Sys")->where(array("name"=>"now_list_time"))->getField("value");
        /*结束时间*/
        $jz_countdown = M("Sys")->where(array("name"=>"jz_countdown"))->getField("value");
        $countdown =  $jz_countdown*60*60;
        $endtime = $lasttime+$countdown;
        /*剩余时间*/
        $second = $endtime - time();
        $this->assign("second",$second);
        $day = floor($second/(3600*24));
        $second = $second%(3600*24);
        $hour = floor($second/3600) + $day*24;
        $second = $second%3600;
        $minute = floor($second/60);
        $second = $second%60;
        $shengyu = $hour.":".$minute.":".$second;
        $this->assign("shengyu",$shengyu);

        $seatlist = M("Seatlist")->order("id desc")->limit(3)->select();
        foreach($seatlist as $k => $v){
            $username = M("User")->where(array("id"=>$v['user_id']))->getField("username");
            $seatlist[$k]['username'] =  change_username($username);
        }
        $this->assign("seatlist",$seatlist);
        $sysnotice = M("Sysnotice")->limit(15)->select();
        $this->assign('sysnotice',$sysnotice);

        $userlist = M("User")->select();
        //业绩比拼，限定最少推荐人数
        $rank_num = M("Sys")->where(array("name"=>'rank_num'))->getField('value');
        //业绩比拼，限定前X名。
        $rank = M("Sys")->where(array("name"=>'ranks'))->getField('value');
        $list = array();
        foreach($userlist as $k => $v){
            if($v['round_child_num'] >= $rank_num){
                $isseat = M("Seatlist")->where(array("user_id"=>$v['id']))->getField('id');
                if($isseat>0){  //推荐者必须有过付费占位记录。
                    $user_name = M("User")->where(array("id"=> $v['id']))->getField('username');
                    $user_name = change_username($user_name);
                    $list[] = array('user'=>$user_name,'num'=>$v['round_child_num'],'time'=>$v['activate_time']);
                }
            }
        }
        array_multisort(array_column($list,'num'),SORT_DESC ,array_column($list,'time'),SORT_ASC ,$list); /*按推荐数、占位时间排序*/

        $list =  array_slice($list, 0,$rank); /*取排名前X*/
        $this->assign('list',$list);

        $this->display();
    }

   /* YPP 占位
       array(1 => '点位奖励',2 => '推荐奖励',3 => '进入复投钱包',4 => '占位支付',5 => '进入奖池',6 => '进入业绩比拼',7 => '归平台部分'  );
   */
    public function doseat(){

        $user_id = $_SESSION['userId'];
        if(!$user_id){
            $this->error('请先登陆！', U('User/User/index'));
            die;
        }


        $now_list_time = M("Sys")->where(array("name"=>"now_list_time"))->getField("value");//奖池开启时间
        $jz_countdown = M("Sys")->where(array("name"=>"jz_countdown"))->getField("value");//奖池倒计时
        $endtime = $now_list_time + $jz_countdown*60*60;
        $now = time();
        if($now >= $endtime){
            $this->error('奖池锁定中，请稍后再试！', U('User/User/index'));
            die;
        }


        $user_name = M("user")->where("id = $user_id")->getField('username');
        /* 用户名 隐藏部分邮箱号*/
        $user_name = change_username($user_name);
        $usermoney = M("User")->where(array("id"=> $user_id))->getField('usermoney'); //用户余额

        $seat_on = M("Sys")->where(array("name"=> 'seat_on'))->getField('value'); //占位开启状态
        $seatmoney = M("Sys")->where(array("name"=> 'seat_money'))->getField('value'); //占位需支付金额
        $in_sys = M("Sys")->where(array("name"=> 'in_sys'))->getField('value');   //归平台部分
        $in_pond = M("Sys")->where(array("name"=> 'in_pond'))->getField('value'); //进入奖池部分
        $in_list = M("Sys")->where(array("name"=> 'in_list'))->getField('value'); //进入业绩比拼部分

        $recommend_on = M("Sys")->where(array("name"=> 'recommend_on'))->getField('value'); //推荐奖开启状态
        $recommend_num = M("Sys")->where(array("name"=> 'recommend_num'))->getField('value'); //推荐奖层级数
        $wallet = M("Sys")->where(array("name"=> 'wallet'))->getField('value'); //奖金一部分进入钱包，用于复投
        $wallet = $wallet/100;
        $wallet_name = M("Sys")->where(array("name"=> 'wallet_name'))->getField('value'); //复投钱包名称
        $now_list_num = M("Sys")->where(array("name"=> 'now_list_num'))->getField('value'); //当前轮次
        $now_yj_time = M("Sys")->where(array("name"=> 'now_yj_time'))->getField('value'); //当前业绩大比拼轮次
        $is_ft = 0;//钱包复投
        if($seat_on != 1){
            $this->error('捐赠时间未到，请稍后再试！', U('User/User/index'));
            die;
        }else if($seatmoney>$usermoney){
            $this->error('您的余额不足！请先充值');
            die;
        }else{
            $seat = M("Seatlist");
            $parent_id = M("user")->where("id = $user_id")->getField('parent');
            if(!$parent_id){
                $parent_id = 0;
            }
                $nowseat = $seat->where(array("list_num"=>$now_list_num))->order('id desc')->limit(1)->select(); //当前占位者所在位置。


/*            if($nowseat[0]['line'] == 15 && $nowseat[0]['seat'] == 16384){
                $this->error('捐赠失败!已排至最末位，请等待下一轮！');
                die;
            }*/
                $data['user_id'] = $user_id;
                $data['parent_id'] = $parent_id;
                $data['time'] = time();
                if(!$nowseat){  //没有占位者。
                    $data['line'] = 1;
                    $data['seat'] = 1;
                    $data['tree_id'] = 0;
                }else{
                    if($nowseat[0]['line'] ==1){
                        $line_num = 1;
                    }else{
                        $line_num = pow(2,$nowseat[0]['line']-1); //当前行总位数 =  2 的当前行数-1 次方
                    }
                    $seat = $nowseat[0]['seat'];       //当前最后一个占位。

                    if($seat == $line_num)          //当前行最后一个位置已经被占。新起一行。
                    {
                        $data['line'] = $nowseat[0]['line']+1;
                        $data['seat'] = 1;
                        $data['tree_id'] = M("Seatlist")->where(array('line' => $nowseat[0]['line'],'seat'=>1,"list_num"=>$now_list_num))->getField('user_id');
                    }else{                           //当前行未占满，往后排。
                        $data['line'] = $nowseat[0]['line'];
                        $data['seat'] = $nowseat[0]['seat']+1;
                        //应归在哪个树状ID下
                        $theseat = $nowseat[0]['seat']/2;
                        if($nowseat[0]['line'] == 2){
                            $line = 1;
                            $theseat = 1;
                        }else{
                            $line = $nowseat[0]['line']-1;
                            if($theseat < 1){
                                $theseat = 1;
                            }elseif($theseat >= 1){
                                $theseat = intval($theseat)+1;
                            }
                        }
                        $data['tree_id'] = M("Seatlist")->where(array('line' => $line ,'seat'=>$theseat,"list_num"=>$now_list_num))->getField('user_id');
                    }
                }
                $data['seat_money'] = M("Sys")->where(array("name"=>"seat_money"))->getField("value");
                $data['list_num'] = $now_list_num;
                $data['yj_list_num'] = $now_yj_time;
                $res = M("Seatlist")->add($data);
                //占位成功
                if($res){
                    add_log($user_id,-$seatmoney,0,4,"捐赠占位-".$seatmoney);
                    //奖池更新时间
                    $now_list_timea['value'] = time();
                    M("Sys")->where(array("name"=>"now_list_time"))->save($now_list_timea);

                    $seat_num = M("Sys")->where(array("name"=>"seat_num"))->getField("value"); //点位奖层数
                    //$recommend_on == 0 关闭推荐奖  1 开启推荐奖  2 只有推荐奖
                    if($recommend_on != 2){
                        /*占位成功，给所有树状上级分点位奖*/
                        $newseat =  M("Seatlist")->where(array('user_id' => $user_id ,'list_num'=>$now_list_num))->order("id desc")->limit(1)->select();
                        $line = $newseat[0]['line'];
                        $seat = $newseat[0]['seat'];
                        $tree_id = array();
                        if($line>1){
                            if($line > 2){
                               // for($i=0;$i<$line+1;$i++){
                                for($i=0;$i<$seat_num;$i++){
                                    $line = $line - 1;
                                    $seat = round($seat/2);
                                    $tree_id[] = M("Seatlist")->where(array('line' => $line ,'seat'=>$seat ,'list_num'=>$now_list_num))->getField('user_id');
                                }
                            }else{
                                $tree_id[] = M("Seatlist")->where(array('line' => 1 ,'seat'=>1 ,'list_num'=>$now_list_num))->getField('user_id');
                            }
                        }
                        $class = M("Userclass")->select();
                        foreach($tree_id as $k=>$v){
                            if($v>0){
                            $userclass =  M("User")->where(array('id' => $v))->getField('user_class');
                            $wallet1 = $class[$userclass-1]['class_reward'] * $wallet;     //进入钱包部分
                                $wallet1= sctonum($wallet1);
                            $money = $class[$userclass-1]['class_reward'] - $wallet1;
                                $money = sctonum($money);
                            $amount = $class[$userclass-1]['class_reward'];
                                $amount = sctonum($amount);
                            //点位奖励进入用户余额。（奖励 == 奖励 - 进入钱包）
                            M("User")->where(array('id' => $v))->setInc('usermoney',$money);
                           /* 插入记录*/
                            $ceng = $k+1;
                            add_log($v,$money,$amount, 1,"点位奖励，来自-$user_name ，第 $ceng 层");
                            //指定获得奖励的一部分，进入XX钱包用于复投。
                            M("User")->where(array('id' => $v))->setInc('freeze_money',$wallet1);
                            /* 插入记录*/
                            add_log($v,$wallet1,0,3, "回购-来自$user_name");
                            }
                        }
                    }
                    if($recommend_on != 0){
                        /*占位成功，给推荐上级分推荐奖*/
                        $parents = array();
                        $j = $recommend_num;   //推荐奖层级数
                        $uid = $user_id;

                        //获取指定层级推荐上家
                        for($i=0;$i<$j;$i++){
                            $uid = M('User')->where(array('id' => $uid))->getField('parent');
                            if($uid){
                                $parents[] = $uid;
                            }
                        }

                        $newarray = array();
                        $parent = 0;
                        foreach($parents as $k=>$v){
                          if($v != $parent){
                              $newarray[] = $v;
                              $parent = $v;
                          }
                        }
                        $parents = $newarray;



                        if($is_ft == 1){
                            //把自己加入推荐人行列，去掉最后一级推荐人。
                            array_unshift($parents, $user_id);
                            array_pop ($parents);
                        }

                        $a = 0;
                        $all_sy = M("Log")->where(array("user_id" => $user_id, "type" => array("in", "1,2,3,8,9")))->getField("money", true);
                        //$all_sy = (array_sum($all_sy) > 0) ? array_sum($all_sy) : 0;
                        $all_sy = ypp_array_sum($all_sy);
                        foreach($parents as $k =>$v){
                            /*  if($all_sy < $seatmoney){   //用户总收益少于捐赠金额,只要捐赠过*/
                            $isseat = M("User")->where(array("id" => $v))->getField('activate_time');
                            /*}else{                     //用户总收益达到捐赠金额,必须本轮也捐赠过。
                                $isseat = M("Seatlist")->where(array("user_id" => $v,'list_num'=>$now_list_num))->getField('id');
                            }*/
                            $a = $a+1;
                         if($isseat>0) {  //推荐者必须有过付费占位记录。
                            $recommend = M('Sys')->where(array('name' => 'recommend_'.$a))->getField('value');
                            $wallet2 = $recommend * $wallet; //进入复投钱包部分
                               $wallet2= sctonum($wallet2);
                            $money = $recommend - $wallet2;
                               $money= sctonum($money);
                            $amount = $recommend;
                               $amount= sctonum($amount);

                                M("User")->where(array('id' => $v))->setInc('usermoney', $money);
                                /* 插入记录*/
                                $ceng = $k+1;
                                add_log($v, $money,$amount, 2, "推荐奖励，来自$ceng 级好友$user_name");
                                //指定获得奖励的一部分，进入XX钱包用于复投。
                                M("User")->where(array('id' => $v))->setInc('freeze_money', $wallet2);
                                add_log($v, $wallet2,0, 3, "回购-来自$user_name");
                         }
                        }
                        //获取所有推荐上家
                        /*$parent = 1;
                          while($parent==1){
                            $uid = M('User')->where(array('id' => $uid))->getField('parent');
                            if($uid){
                                $parents[] = $uid;
                                $parent = 1;
                            }else{
                                $parent = 0;
                            }
                        }*/
                    }
                    M("User")->where(array('id' => $user_id))->setDec('usermoney',$seatmoney);

                    $pond = M("Sys")->where(array('name' => 'pond'))->getField("value");
                    $p['value'] = sctonum($pond+$in_pond);
                    M("Sys")->where(array('name' => 'pond'))->save($p);
                    $list = M("Sys")->where(array('name' => 'list'))->getField("value");
                    $l['value'] = sctonum($list+$in_list);
                    M("Sys")->where(array('name' => 'list'))->save($l);

                    M("User")->where(array('id' => 1))->setInc('usermoney',$in_sys);
                    add_log(1,$in_sys,0,7,"归平台部分，来自-".$user_name);
                    add_log(0,$in_pond,0,5,"进入奖池，来自-".$user_name);
                    add_log(0,$in_list,0,6,"进入业绩比拼，来自-".$user_name);

                    $seatnum = M('Seatlist')->where(array("user_id" =>$user_id ,"yj_list_num"=>$now_yj_time))->getField('id',true);
                    $seatnum = count($seatnum);

                    $activate_time = M("User")->where(array("id"=>$user_id))->getField("activate_time");
                    if($activate_time>0){
                        $act['activate_time'] = $activate_time; //首次捐赠激活时间。
                    }else{
                        $act['activate_time'] = time(); //首次捐赠激活时间。
                    }
                    M("User")->where(array("id"=>$user_id))->save($act);
                    //if($seatnum == 1){  //本轮业绩大比拼首次捐赠占位, 上级本轮推荐人数加1，用于业绩大比拼

                 if($user_id != 1){
                    //上级捐赠过
                    $parentid = M('User')->where("id = $user_id")->getField('parent');
                    //上级是否捐赠过
                    $is_seat = M("User")->where("id = $parentid")->getField("activate_time");
                    //上级捐赠之后，本人本轮没有过捐赠记录
                    $is_yj_add = M('Seatlist')->where(array("user_id" =>$user_id ,"time"=>array('gt',$is_seat),"yj_list_num"=>$now_yj_time))->getField('id',true);


                    if($is_seat>0 && count($is_yj_add)<2){
                        $now_yj_time = M("Sys")->where(array("name"=>"now_yj_time"))->getField("value");
                        $yeji['yeji_id'] = $now_yj_time;
                        $yeji['user_id'] = $parentid;
                        $yejinum = M("Yeji")->where(array("yeji_id"=>$now_yj_time,"user_id"=>$parentid))->getField("num");

                        M('User')->where("id = $parentid")->setInc('round_child_num',1);
                        if(empty($yejinum)){
                            $yeji['num'] = 1;
                            M("Yeji")->add($yeji);
                        }else{
                            $yeji['num'] = $yejinum + 1;
                            M("Yeji")->where(array("yeji_id"=>$now_yj_time,"user_id"=>$parentid))->save($yeji);
                        }

                 }
                    /*查询上级是否满足升级条件*/
                    $userclass = M('Userclass')->select();
                    $child_num = M('User')->where(array("parent"=>$parent_id,"activate_time"=>array("gt",0)))->getField("id",true);
                    $child_num = count($child_num);//上级的推荐人数
                    foreach($userclass as $k=>$v){
                        $need_num = $v['need_num'];
                        if($child_num >= $need_num){   //当上级的推荐人数满足升级条件。
                            $c['user_class'] = $v['class'];
                            M("User")->where(array("id"=>$parent_id))->save($c);
                        }
                    }
                  }

                    $map['freeze_money'] = array("egt",$seatmoney);
                    $alluser = M("User")->where($map)->select();
                    //$alluser = M("User")->where(array("freeze_money"=>array("egt",$seatmoney)))->select();

                    foreach($alluser as $k=>$v){
                        $this->redoseat($v['id']);
                    }
                    $this->success('捐赠成功!', U('User/User/index'));
                }else{
                    $this->error('捐赠失败!稍后重试');
                    die;
                }
            }
    }


    public function redoseat($userid){
        $user_id = $userid;
        $user_name = M("user")->where("id = $user_id")->getField('username');
        /* 用户名 隐藏部分邮箱号*/
        $user_name = change_username($user_name);

        $freeze_money = M("user")->where("id = $user_id")->getField('freeze_money');
        $seatmoney = M("Sys")->where(array("name"=> 'seat_money'))->getField('value'); //占位需支付金额

        if($freeze_money < $seatmoney){
            $this->success('捐赠成功!', U('User/User/index'));
            die();
        }



        $in_sys = M("Sys")->where(array("name"=> 'in_sys'))->getField('value');   //归平台部分
        $in_pond = M("Sys")->where(array("name"=> 'in_pond'))->getField('value'); //进入奖池部分
        $in_list = M("Sys")->where(array("name"=> 'in_list'))->getField('value'); //进入业绩比拼部分

        $recommend_on = M("Sys")->where(array("name"=> 'recommend_on'))->getField('value'); //推荐奖开启状态
        $recommend_num = M("Sys")->where(array("name"=> 'recommend_num'))->getField('value'); //推荐奖层级数
        $wallet = M("Sys")->where(array("name"=> 'wallet'))->getField('value'); //奖金一部分进入钱包，用于复投
        $wallet = $wallet/100;
        $wallet_name = M("Sys")->where(array("name"=> 'wallet_name'))->getField('value'); //复投钱包名称
        $now_list_num = M("Sys")->where(array("name"=> 'now_list_num'))->getField('value'); //当前轮次
        $now_yj_time = M("Sys")->where(array("name"=> 'now_yj_time'))->getField('value'); //当前业绩大比拼轮次
        $is_ft = 1;//钱包复投

            $seat = M("Seatlist");
            $parent_id = M("User")->where("id = $user_id")->getField('parent');
        if(!$parent_id){
            $parent_id =0;
        }
            $nowseat = $seat->where(array("list_num"=>$now_list_num))->order('id desc')->limit(1)->select(); //当前占位者所在位置。


      /*  if($nowseat[0]['line'] == 15 && $nowseat[0]['seat'] == 16384){
            $this->error('捐赠失败!已排至最末位，请等待下一轮！');
            die;
        }*/

            $data['user_id'] = $user_id;
            $data['parent_id'] = $parent_id;
            $data['time'] = time();
            if(!$nowseat){  //没有占位者。
                $data['line'] = 1;
                $data['seat'] = 1;
                $data['tree_id'] = 0;
            }else{
                if($nowseat[0]['line'] ==1){
                    $line_num = 1;
                }else{
                    $line_num = pow(2,$nowseat[0]['line']-1); //当前行总位数 =  2 的当前行数-1 次方
                }
                $seat = $nowseat[0]['seat'];       //当前最后一个占位。

                if($seat == $line_num)          //当前行最后一个位置已经被占。新起一行。
                {
                    $data['line'] = $nowseat[0]['line']+1;
                    $data['seat'] = 1;
                    $data['tree_id'] = M("Seatlist")->where(array('line' => $nowseat[0]['line'],'seat'=>1,"list_num"=>$now_list_num))->getField('user_id');
                }else{                           //当前行未占满，往后排。
                    $data['line'] = $nowseat[0]['line'];
                    $data['seat'] = $nowseat[0]['seat']+1;
                    //应归在哪个树状ID下
                    $theseat = $nowseat[0]['seat']/2;
                    if($nowseat[0]['line'] == 2){
                        $line = 1;
                        $theseat = 1;
                    }else{
                        $line = $nowseat[0]['line']-1;
                        if($theseat < 1){
                            $theseat = 1;
                        }elseif($theseat >= 1){
                            $theseat = intval($theseat)+1;
                        }
                    }
                    $data['tree_id'] = M("Seatlist")->where(array('line' => $line ,'seat'=>$theseat,"list_num"=>$now_list_num))->getField('user_id');
                }
            }
            $data['seat_money'] = M("Sys")->where(array("name"=>"seat_money"))->getField("value");
            $data['list_num'] = $now_list_num;
            $data['yj_list_num'] = $now_yj_time;
            $res = M("Seatlist")->add($data);
            //占位成功
            if($res) {
                add_log($user_id, -$seatmoney,0, 13, "复投钱包自动捐赠占位-" . $seatmoney);
                //奖池更新时间
                $now_list_timea['value'] = time();
                M("Sys")->where(array("name" => "now_list_time"))->save($now_list_timea);

                $seat_num = M("Sys")->where(array("name" => "seat_num"))->getField("value"); //点位奖层数
                //$recommend_on == 0 关闭推荐奖  1 开启推荐奖  2 只有推荐奖
                if ($recommend_on != 2) {
                    /*占位成功，给所有树状上级分点位奖*/
                    $newseat = M("Seatlist")->where(array('user_id' => $user_id, 'list_num' => $now_list_num))->order("id desc")->limit(1)->select();
                    $line = $newseat[0]['line'];
                    $seat = $newseat[0]['seat'];
                    $tree_id = array();
                    if ($line > 1) {
                        if ($line > 2) {
                            // for($i=0;$i<$line+1;$i++){
                            for ($i = 0; $i < $seat_num; $i++) {
                                $line = $line - 1;
                                $seat = round($seat / 2);
                                $tree_id[] = M("Seatlist")->where(array('line' => $line, 'seat' => $seat, 'list_num' => $now_list_num))->getField('user_id');
                            }
                        } else {
                            $tree_id[] = M("Seatlist")->where(array('line' => 1, 'seat' => 1, 'list_num' => $now_list_num))->getField('user_id');
                        }
                    }
                    $class = M("Userclass")->select();
                    foreach ($tree_id as $k => $v) {
                        if ($v > 0) {
                            $userclass = M("User")->where(array('id' => $v))->getField('user_class');
                            $wallet1 = $class[$userclass - 1]['class_reward'] * $wallet;     //进入钱包部分
                              $wallet1= sctonum($wallet1);
                            $money = $class[$userclass - 1]['class_reward'] - $wallet1;
                              $money= sctonum($money);
                            $amount = $class[$userclass - 1]['class_reward'];
                              $amount= sctonum($amount);
                            //点位奖励进入用户余额。（奖励 == 奖励 - 进入钱包）
                            M("User")->where(array('id' => $v))->setInc('usermoney', $money);
                            /* 插入记录*/
                            $ceng = $k+1;
                            add_log($v, $money,$amount, 1, "点位奖励，来自-$user_name ，第 $ceng 层");
                            //指定获得奖励的一部分，进入XX钱包用于复投。
                            M("User")->where(array('id' => $v))->setInc('freeze_money', $wallet1);
                            /* 插入记录*/
                            add_log($v, $wallet1,0, 3,"回购-来自$user_name");
                        }
                    }
                }
                if ($recommend_on != 0) {
                    /*占位成功，给推荐上级分推荐奖*/
                    $parents = array();

                    $j = $recommend_num;   //推荐奖层级数
                    $uid = $user_id;

                    //获取指定层级推荐上家
                    for ($i = 0; $i < $j; $i++) {
                        $uid = M('User')->where(array('id' => $uid))->getField('parent');
                        if ($uid) {
                            $parents[] = $uid;
                        }
                    }

                    if ($is_ft == 1) {
                        //把自己加入推荐人行列，去掉最后一级推荐人。
                        array_unshift($parents, $user_id);
                        array_pop($parents);
                    }

                    $a = 0;
                    $all_sy = M("Log")->where(array("user_id" => $user_id, "type" => array("in", "1,2,3,8,9")))->getField("money", true);
                    //$all_sy = (array_sum($all_sy) > 0) ? array_sum($all_sy) : 0;
                    $all_sy = ypp_array_sum($all_sy);
                    foreach ($parents as $k => $v) {

                        /*  if($all_sy < $seatmoney){   //用户总收益少于捐赠金额,只要捐赠过*/
                        $isseat = M("User")->where(array("id" => $v))->getField('activate_time');
                        /*}else{                     //用户总收益达到捐赠金额,必须本轮也捐赠过。
                            $isseat = M("Seatlist")->where(array("user_id" => $v,'list_num'=>$now_list_num))->getField('id');
                        }*/

                        $a = $a+1;
                        if ($isseat > 0) {  //推荐者必须有过付费占位记录。

                        $recommend = M('Sys')->where(array('name' => 'recommend_' . $a))->getField('value');
                        $wallet2 = $recommend * $wallet; //进入复投钱包部分
                          $wallet2= sctonum($wallet2);
                        $money = $recommend - $wallet2;
                          $money= sctonum($money);
                        $amount = $recommend;
                          $amount= sctonum($amount);



                            M("User")->where(array('id' => $v))->setInc('usermoney', $money);
                            /* 插入记录*/
                            $ceng = $k+1;
                            if($ceng == 1 ){
                                add_log($v, $money,$amount, 2, $wallet_name."，复投奖励");
                            }else{
                                $ceng = $ceng-1;
                                add_log($v, $money,$amount, 2, "推荐奖励，来自$ceng 级好友$user_name");
                            }

                            //指定获得奖励的一部分，进入XX钱包用于复投。
                            M("User")->where(array('id' => $v))->setInc('freeze_money', $wallet2);
                            add_log($v, $wallet2,0, 3,"回购来自-$user_name");
                        }
                    }
                    //获取所有推荐上家
                    /*$parent = 1;
                      while($parent==1){
                        $uid = M('User')->where(array('id' => $uid))->getField('parent');
                        if($uid){
                            $parents[] = $uid;
                            $parent = 1;
                        }else{
                            $parent = 0;
                        }
                    }*/
                }
                M("User")->where(array('id' => $user_id))->setDec('freeze_money', $seatmoney);

                $pond = M("Sys")->where(array('name' => 'pond'))->getField("value");
                $p['value'] = sctonum($pond+$in_pond);
                M("Sys")->where(array('name' => 'pond'))->save($p);
                $list = M("Sys")->where(array('name' => 'list'))->getField("value");
                $l['value'] = sctonum($list+$in_list);
                M("Sys")->where(array('name' => 'list'))->save($l);

                M("User")->where(array('id' => 1))->setInc('usermoney', $in_sys);
                add_log(1, $in_sys,0, 7, "归平台部分，来自-" . $user_name);
                add_log(0, $in_pond, 0,5, "进入奖池，来自-" . $user_name);
                add_log(0, $in_list,0, 6, "进入业绩比拼，来自-" . $user_name);


            }

        $map['freeze_money'] = array("egt",$seatmoney);
       //$alluser = M("User")->where(array("freeze_money"=>array("egt",$seatmoney)))->select();
        $alluser = M("User")->where($map)->select();
        foreach($alluser as $k=>$v){
            $this->redoseat($v['id']);
        }
    }


     /*
     * 奖池倒计时结束执行
     */
/*    public function countdown(){
        $time = time();
        //本轮开始时间
        $now_list_time = M("Sys")->where(array("name"=> 'now_list_time'))->getField('value');
        //奖池周期（小时）
        $jz_countdown = M("Sys")->where(array("name"=>"jz_countdown"))->getField('value');
        //转换为秒
        $jz_countdown = 60*60*$jz_countdown;
        //本轮结束时间
        $end_jz_time = $now_list_time+$jz_countdown-1;

        if($time >= $end_jz_time){
            $now_list_num = M("Sys")->where(array("name"=> 'now_list_num'))->getField('value'); //当前轮次
            //最后一位占位者
            $lastseat = M("Seatlist")->where(array("list_num"=>$now_list_num))->order("time desc")->limit(1)->getField("user_id");
            if(!$lastseat){
                $this->error('本轮无捐赠者！');
                die;
            }
            //奖池
            $seat = M("Sys")->where(array("name"=>"pond"))->getField("value");
            //奖池奖励进入用户余额。
            M("User")->where(array('id' => $lastseat))->setInc('usermoney',$seat);
            //插入记录
            add_log($lastseat,$seat,0,8,$now_list_num."轮 奖池结算奖励，获得".$seat);
            $pond['value'] = 0;
            $now_jz_time['value'] = time();
            M("Sys")->where(array("name"=>"pond"))->save($pond);
            M("Sys")->where(array("name"=>"now_list_time"))->save($now_jz_time);
            M("Sys")->where(array("name"=>"now_list_num"))->setInc('value',1);
            $this->success('本轮捐赠奖励结束！', U('Index/index'));
        }

    }*/
    /*
    * 业绩大比拼计时结束执行
    */
/*    public function yjcountdown(){
        $time = time();
        //当前业绩大比拼开始时间
        $now_yj_time = M("Sys")->where(array("name"=> 'now_yj_time'))->getField('value');
        //业绩大比拼周期（天）
        $yj_countdown = M("Sys")->where(array("name"=>"yj_countdown"))->getField('value');
        $yj_countdown = 60*60*24*$yj_countdown;
        //本轮业绩大比拼结束时间
        $end_yj_time = $now_yj_time+$yj_countdown-1;

        //if($time >= $end_yj_time){
            //业绩比拼奖池金额
            $list_pond = M("Sys")->where(array("name"=>"list"))->getField('value');
            //前10名额外获得比例
            $rank_deuce = M("Sys")->where(array("name"=>"rank_deuce"))->getField('value');
            //前10名奖励
            $pond2 = $list_pond * $rank_deuce/100;
            //平分奖励
            $pond1 = $list_pond - $pond2;

            $userlist = M("User")->select();
            //业绩比拼，限定最少推荐人数
            $rank_num = M("Sys")->where(array("name" => 'rank_num'))->getField('value');
            //业绩比拼，限定前X名。
            $rank = M("Sys")->where(array("name" => 'ranks'))->getField('value');
            $list = array();
            foreach ($userlist as $k => $v) {
                if ($v['round_child_num'] >= $rank_num) {
                    $isseat = M("Seatlist")->where(array("user_id" => $v['id']))->getField('id');
                    if ($isseat > 0) {  //推荐者必须有过付费占位记录。
                        $user_name = M("User")->where(array("id" => $v['id']))->getField('username');
                        $user_name = change_username($user_name);
                        $list[] = array('uid' => $v['id'],'user' => $user_name, 'num' => $v['round_child_num'], 'time' => $v['activate_time']);
                    }
                }
            }
            array_multisort(array_column($list, 'num'), SORT_DESC, array_column($list, 'time'), SORT_DESC, $list); //按推荐数、占位时间排序
            //业绩比拼全部获奖者
            $list1 = array_slice($list, 0, $rank); //取排名前X
            $list2 = array_slice($list, 0, 10);    //取排名前10名
            $num1 = count($list1); //平分人数
            $num2 = count($list2); //前10人数
            //每人获得奖励
            $pond1 =  round($pond1/$num1,8);
            //前10获得奖励
            $pond2 =  round($pond2/$num2,8);
            foreach($list1 as $k => $v){
                $uid = $v['uid'];
                M("User")->where(array('id' => $uid))->setInc('usermoney',$pond1);
                //插入记录
                add_log($uid,$pond1,0,9,$now_yj_time."期 业绩大比拼结算奖励，获得".$pond1);
            }

            foreach($list2 as $k => $v){
                $uid = $v['uid'];
                M("User")->where(array('id' => $uid))->setInc('usermoney',$pond2);
                //插入记录
                add_log($uid,$pond2,0,9,$now_yj_time."期 业绩大比拼前10名奖励，获得".$pond2);
            }

            foreach($userlist as $k => $v){
                $data['round_child_num'] = 0;
                M("User")->where(array('id' => $v['id']))->save($data);
            }


            $yj_time['value'] = strtotime(date('Y-m-d', time()));
            $yj_pond['value'] = 0;
            M("Sys")->where(array("name" => "now_yj_time" ))->save($yj_time);
            M("Sys")->where(array("name" => "list" ))->save($yj_pond);
            $this->success('本轮业绩大比拼结束！', U('Index/index'));
        //}
    }*/

    public function makecode(){
        //产生随机验证码字符
        $str="123456789abcdefghijkmnpqrstuvwxyz";
        $str=str_shuffle($str);
        $code=substr($str, 0,4);

        session_start();
        $_SESSION['code']=$code;
//创建画布
        $image=imagecreatetruecolor(100,30);

        $gray = imagecolorallocate($image,121,121,121);

// 填充画布背景
        imagefill($image,0,0,$gray);


//随机产生字体颜色
        function randtextcolor($image){
            return imagecolorallocate($image, 255, 255, 255);
        }

        //开始往画布上写字
        imagestring($image,12, 35, 8, $code, randtextcolor($image));

//产生5条干扰线


        //告诉浏览器以image/png的形式返回
        header("Content-Type: image/png");

        //返回图片
        imagepng($image);

//销毁图片资源
        imagedestroy($image);
    }
    public function ltcjob(){
        ltcjob();
        $this->scqbdz();
    }

    function scqbdz(){
        $where['qbdz'] = array("exp",'is null');
        $where1['qbdz'] = array("eq",'');
        $where_main['_complex'] = array(
            $where,
            $where1,
            '_logic' => 'or'
        );
        $list = M("User")->where($where_main)->select();

        foreach($list as $k => $v){
            $res = createnewaccount($v['username']);
            if($res['error'] == 0){
               M('User')->where(array('username' => $v['username']))->save(array('qbdz' => $res['qbdz']));
            }
        }
    }

}